<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<html>
<head>
    <title>商品管理</title>
    <meta name="decorator" content="default"/>
    <script>
        function deletAttr(obj){
            if(obj!=0){
                $("div#"+obj).remove();
            }else{
                alert("必须保留一个！");
            }
        }
        //添加商品属性
        var productAttr=1;
        $(document).on("click", "#addAttribute", function () {
            var grorpLength=$("#productAttrLength").val();
            if(grorpLength!=null&&grorpLength!=''&&productAttr==1){
                productAttr=parseInt(grorpLength);
            }
            var _html = '';
            _html +='<div class="controls" id="'+productAttr+'">';
            _html += '<input type="text" placeholder="属性值，例如：红色XL" class="required" minlength="1" name="productAttrGroup['+productAttr+'].sku" value=""/>';
            _html += ' <input type="number" class="required" min="0"  style="width:90px" placeholder="价格"  minlength="1" name="productAttrGroup['+productAttr+'].price" value=""/>';
            _html += ' <input type="text" class="required" style="width:90px"  placeholder="货号"  minlength="1" name="productAttrGroup['+productAttr+'].unit" value=""/>';
            _html += ' <input type="number" class="required" min="1"  style="width:90px"  placeholder="库存量"  minlength="1" name="productAttrGroup['+productAttr+'].storeNum" value=""/>';
            _html += ' <input type="number" class="required" min="1"  style="width:90px"  placeholder="库存预警值"  minlength="1" name="productAttrGroup['+productAttr+'].alertStoreNum" value=""/>';
            _html += ' <input type="button" onclick="deletAttr('+productAttr+');" value="删除"><br/><br/>';
            _html +='</div>';
            var option=$("#control_group_").append(_html);
            productAttr++;
            $("#productAttrLength").val(productAttr);
        });
        $(function() {
        //判断代理商是否是这个区域唯一的
        $("#barcode").blur(function() {
            var reverflag=$("#categoryIdId").val();
            var barcode=$("#barcode").val();
            $.ajax({
                type : "POST",
                url : "${ctx}/sys/product/checkCategory",
                data : "barcode="+barcode+"&reverflag="+reverflag,
                success : function(date) {
                    if(date=='0'){
                        document.getElementById("agent").innerHTML="*";
                    }else {
                        location.href="${ctx}/sys/product/form?id="+date;

                    }
                }

            });

        });
        });
    </script>
</head>
<body>
<ul class="nav nav-tabs">
    <li><a href="${ctx}/sys/product/showProductList">商品列表</a></li>
    <li class="active"><a href="${ctx}/sys/product/form?id=${tbProduct.id}">商品添加</a></li>
</ul>
<br/>
<form:form id="inputForm" modelAttribute="tbProduct" action="${ctx}/sys/product/productEdit" method="post"
           class="form-horizontal" enctype="multipart/form-data">
    <form:hidden path="id"/>
    <sys:message content="${message}"/>
    <div class="control-group">
        <label class="control-label">类别:</label>
        <div class="controls">
            <sys:treeselect id="categoryId" name="categoryId" value="${category.id}" labelName="parent.name"
                            labelValue="${category.name}" notAllowSelectParent="true" notAllowSelectRoot="true"
                            title="类别" url="/sys/category/treeData1" extId="${category.id}" cssClass="required" />
            <span class="help-inline"><font color="red">*</font> </span>
        </div>
    </div>
    <div class="control-group">
        <label class="control-label">条形码:</label>
        <div class="controls">
            <form:input path="barcode" id="barcode" htmlEscape="false" maxlength="50" class="required"/>
            <span class="help-inline"><font color="red" id="agent">*</font> </span>
        </div>
    </div>
    <div class="control-group">
        <label class="control-label">商品名称:</label>
        <div class="controls">
            <form:input path="title" id="title" htmlEscape="false" maxlength="50" class="required"/>
            <span class="help-inline"><font color="red">*</font> </span>
        </div>
    </div>
    <div class="control-group">
        <label class="control-label">排序:</label>
        <div class="controls">
            <form:input path="proSort" id="proSort" htmlEscape="false" maxlength="50" class="required"/>
            <span class="help-inline"><font color="red">*</font> </span>
        </div>
    </div>
    <div class="control-group">
        <label class="control-label">商品单位:</label>
        <div  class="controls">
            <form:input path="size" id="size" htmlEscape="false" maxlength="50" class="required"/>
            <span class="help-inline"><font color="red">*</font> </span>
        </div>
    </div>
    <div class="control-group" style="display: none;" id="kucun">
        <label class="control-label">是否维护库存:</label>
        <div id="weihukucunId" class="controls">
            <form:radiobuttons path="isMaintainStoreNum" id="isMaintainStoreNum" items="${fns:getDictList('yes_no')}"
                               itemLabel="label"
                               itemValue="value" htmlEscape="false" class="required"/>
            <span class="help-inline"><font color="red">*</font> </span>
        </div>
    </div>
        <div class="control-group" id="day" style="display: none;">
            <label class="control-label">是否每天：</label>
            <div class="controls" >
                <input type="checkbox" name="gender" checked="checked" id="che" onchange="chage()">
            </div>
        </div>
        <div id="timeYear" style="display: none;">
            <div class="control-group">
                <label class="control-label">预定开始时间：</label>
                <div class="controls">
                    <input name="reserveStartTime01" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate"
                           value="<fmt:formatDate value="${tbProduct.reserveStartTime}" pattern="yyyy-MM-dd HH:mm:ss"/>"
                           onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false});"/>
                </div>
            </div>
            <div class="control-group">
                <label class="control-label">预定结束时间：</label>
                <div class="controls">
                    <input name="reserveEndTime01" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate"
                           value="<fmt:formatDate value="${tbProduct.reserveEndTime}" pattern="yyyy-MM-dd HH:mm:ss"/>"
                           onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false});"/>
                </div>
            </div>
        </div>
        <div id="timeDay" style="display: none;">
            <div class="control-group">
                <label class="control-label">预定开始时间：</label>
                <div class="controls">
                    <input name="reserveStartTime02" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate"
                           value="<fmt:formatDate value="${tbProduct.reserveStartTime}" pattern="HH:mm"/>"
                           onclick="WdatePicker({dateFmt:'HH:mm',isShowClear:false});"/>
                </div>
            </div>
            <div class="control-group">
                <label class="control-label">预定结束时间：</label>
                <div class="controls">
                    <input name="reserveEndTime02" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate"
                           value="<fmt:formatDate value="${tbProduct.reserveEndTime}" pattern="HH:mm"/>"
                           onclick="WdatePicker({dateFmt:'HH:mm',isShowClear:false});"/>
                </div>
            </div>
        </div>
    <div class="control-group">
        <label class="control-label">是否可用物业钱包:</label>
        <div class="controls">
            <form:radiobuttons path="isUseMqWallet" id="isUseMqWallet" items="${fns:getDictList('yes_no')}"
            itemLabel="label"
            itemValue="value"
            htmlEscape="false" class="required"/>
            <span class="help-inline"><font color="red">*</font> </span>
        </div>
    </div>
    <div class="control-group">
        <label class="control-label">添加商品属性:</label>
        <div class="controls">
            <input type="button" id="addAttribute" name="addAttribute" value="添加"/>
            <span class="help-inline"><font color="red">*</font> </span>
        </div>
    </div>
    <div id="control_group_" class="control-group">
        <c:if test="${flag==1}">
            <c:forEach items="${tbProduct.tbAgentProduct}" var="attr" varStatus="a">
                <div class="controls" id="${a.index}">
                    <input type="text" placeholder="属性值，例如：红色XL" minlength="1" class="required" name="productAttrGroup[${a.index}].sku" value="${attr.attr}"/>
                    <input type="number" min="0" class="required" style="width:90px" placeholder="价格"  minlength="1" name="productAttrGroup[${a.index}].price" value="${attr.price}"/>
                    <input type="text" class="required" style="width:90px"  placeholder="货号" minlength="1"  name="productAttrGroup[${a.index}].unit" value="${attr.unit}"/>
                    <input type="number" class="required" min="1" style="width:90px"  placeholder="库存量" minlength="1"  name="productAttrGroup[${a.index}].storeNum" value="${attr.storeNum}"/>
                    <input type="number" class="required" min="1" style="width:90px"  placeholder="库存预警值" minlength="1"  name="productAttrGroup[${a.index}].alertStoreNum" value="${attr.alertStoreNum}"/>
                    <input type="button" class="required" name="deleteOption"  onclick="deletAttr(${a.index});" value="删除"><br/>
                    <input type="hidden" id="productAttrLength" name ="productAttrLength" value="${listLength}"/>
                 </div><br/>
            </c:forEach>
        </c:if>
        <c:if test="${flag==0}">
                <div class="controls" id="0">
                    <input type="text" class="required" placeholder="属性值，例如：红色XL" name="productAttrGroup[0].sku" value=""/>
                    <input type="number" class="required" min="0" style="width:90px" placeholder="价格" name="productAttrGroup[0].price" value=""/>
                    <input type="text" class="required" style="width:90px"  placeholder="货号" name="productAttrGroup[0].unit" value=""/>
                    <input type="number" class="required" min="1" style="width:90px"  placeholder="库存量" name="productAttrGroup[0].storeNum" value=""/>
                    <input type="number" class="required" min="1" style="width:90px"  placeholder="库存预警值" name="productAttrGroup[0].alertStoreNum" value=""/><br/><br/>
                </div>
        </c:if>
    </div>
    <div class="control-group">
        <label id="container" class="control-label"><a class="btn btn-default btn-lg " id="pickfiles" href="#">
            <i class="glyphicon glyphicon-plus"></i>
            <span>选择文件</span>
        </a>:</label>
        <input type="hidden" id="imgs3" value="2">
        <div class="controls">
            <ol id="nameImagePreview">
                <c:forEach items="${tbAttachments}" var="img">
                    <li><img src="${img.imageUrl}"
                             url="${img.imageUrl}"
                             style="max-width:100px;max-height:100px;_height:100px;border:0;padding:3px;">
                        <input type="hidden" name="uploadUrl" value="${img.imageUrl}">
                        &nbsp;&nbsp;
                        <a href="javascript:void(0)" name="deleteImg">×</a>
                        <input type="text" value="${img.imageUrl}" class="input-text form-control"/>
                    </li>
                </c:forEach>
            </ol>
            <span class="help-inline"><font color="red" id="imgs">*</font> </span>
        </div>
    </div>

    <div class="control-group">
        <label class="control-label">编辑商品详情:</label>
        <div class="controls">
            <textarea id="fullText" name="productDesc">${tbProduct.productDesc}</textarea>
        </div>
    </div>
    <div class="form-actions"><%--onclick="uploadPhoto();"--%>
            <input id="btnSubmit" class="btn btn-primary" type="button"
                   value="保 存"/>
        <input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/>
    </div>
</form:form>

<script type="text/javascript" src="${ctxStatic}/common/jquery-2.0.0.min.js"></script>

<script type="text/javascript" src="${ctxStatic}/bower_components/moxie.js"></script>
<script type="text/javascript" src="${ctxStatic}/bower_components/plupload.dev.js"></script>
<%--<script type="text/javascript" src="/static/bower_components/plupload/js/plupload.full.min.js"></script>--%>
<script type="text/javascript" src="${ctxStatic}/bower_components/qiniu.js"></script>
<script type="text/javascript" src="${ctxStatic}/jquery-validation/1.11.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="${ctxStatic}/ckeditor/ckeditor.js"></script>
<link href="${ctxStatic}/common/mycss.css" rel="stylesheet" type="css">

<script type="text/javascript">
    var imgs3=$("#imgs3").val();
    if(imgs3==2){
        document.getElementById("imgs").innerHTML="*";
        document.getElementById("imgs").setAttribute("style", "color:red;");
    }
    $('#btnSubmit').click(function () {
        imgs3=$("#imgs3").val();
        if(imgs3==undefined){
            document.getElementById("imgs").innerHTML="商品图片必须选择";
            document.getElementById("imgs").setAttribute("style", "color:red;");
        }else{
            document.getElementById("imgs").innerHTML="*";
            document.getElementById("imgs").setAttribute("style", "color:red;");
        }
        $("#inputForm").submit();
//        $("#barcode").focus();
    });
    $("#inputForm").validate({
        submitHandler: function (form) {
            imgs3=$("#imgs3").val();
            if(imgs3==2){
                loading('正在提交，请稍等...');
                form.submit();
            }

        },
        errorContainer: "#messageBox",
        errorPlacement: function (error, element) {
            $("#messageBox").text("输入有误，请先更正。");
            if (element.is(":checkbox") || element.is(":radio") || element.parent().is(".input-append")) {
                error.appendTo(element.parent().parent());
            } else {
                error.insertAfter(element);
            }
        }
    });
    $(document).on('change', '#categoryId',function(){alert('a');}); // ？哪里定义的
    var oldCategoryId = '';
    var hiddenInputTrigger = function(){
        var newCategoryId = $("#categoryIdId").val();
        if(newCategoryId != oldCategoryId){
            oldCategoryId = newCategoryId;
//            alert("new : " + newCategoryId);
            //变更逻辑写在这里。
            $.ajax({
                type : "POST",
                url : "${ctx}/sys/category/getParCategory",
                data : {"categoryId":newCategoryId},
                success : function(date) {
                    if(date=='3'){//生活预定
                        $("#day").hide();
                        $("#day").show();
                        $("#kucun").hide();
                        if(!($("#che").get(0).checked)){
                            $("#timeDay").hide();
                            $("#timeYear").show();
                        }else{
                            $("#timeDay").show();
                            $("#timeYear").hide();
                        }
                    } else {
                        $("#kucun").show();
                        $("#day").hide();
                        $("#timeDay").hide();
                        $("#timeYear").hide();
                    }
                }
            });
        }
    }
    window.setInterval(function(){
        hiddenInputTrigger();
    },200);
    function chage() {
        if(!($("#che").get(0).checked)){
            $("#timeDay").hide();
            $("#timeYear").show();
        }else{
            $("#timeDay").show();
            $("#timeYear").hide();
        }
    }
    $(document).ready(function () {
        CKEDITOR.replace("fullText");

        $(document).on("click", "A[name='deleteImg']", function () {
            $(this).parent().remove();
        });

        var i = ${productAttrs == null ? 0 : productAttrs};


        $("#value").focus();

        $(document).on("change", ":radio[name='isMaintainStoreNum']", function () {
            if ($(this).val() == 1) {
                $("#kucunID").show();
                $("#yujingID").show();
            } else {
                $("#kucunID").hide();
                $("#yujingID").hide();
            }
        });
    });
</script>
<script>
    /*global Qiniu */
    /*global plupload */
    /*global FileProgress */
    /*global hljs */


    $(function () {
        var uploader = Qiniu.uploader({
            runtimes: 'html5,flash,html4',
            browse_button: 'pickfiles',
            container: 'container',
            drop_element: 'container',
            max_file_size: '1000mb',
            flash_swf_url: 'bower_components/plupload/js/Moxie.swf',
            dragdrop: true,
            chunk_size: '4mb',
            multi_selection: !(mOxie.Env.OS.toLowerCase() === "ios"),
            uptoken_url: '/a/qiniu/upload/token',
            domain: "oframjnn6.bkt.clouddn.com",
            get_new_uptoken: false,
            auto_start: true,
            log_level: 5,
            unique_names: true,
            init: {
                'FilesAdded': function (up, files) {
                    plupload.each(files, function (file) {
                    });
                },
                'BeforeUpload': function (up, file) {
                },
                'UploadProgress': function (up, file) {
                    console.log(up);
                },
                'UploadComplete': function () {
                },
                'FileUploaded': function (up, file, info) {
                },
                'Error': function (up, err, errTip) {

                }
            }
        });

        uploader.bind('FileUploaded', function (up, file, info) {
            $("#imgs3").remove();
            console.log("resp_URL : " + JSON.parse(info.response).key);
            var _url = 'http://oframjnn6.bkt.clouddn.com/' + JSON.parse(info.response).key;
            var _html = '<li><img src="'+_url+'" ' +
                    'url="'+_url+'" ' +
                    'style="max-width:100px;max-height:100px;_height:100px;border:0;padding:3px;"> ' +
                    '<input type="hidden" name="uploadUrl" value="'+_url+'"> ' +
                    '&nbsp;&nbsp;<input type="hidden" id="imgs3" value="2"> ' +
                    '<a href="javascript:void(0)" name="deleteImg">×</a> ' +
                    '<input type="text" value="'+_url+'" class="input-text form-control"/></li>';
            console.log(_html);
            $("#nameImagePreview").append(_html);
            document.getElementById("imgs").innerHTML="*";
            document.getElementById("imgs").setAttribute("style", "color:red;");
        });

    });

</script>
</body>
</html>